# -*- coding: utf-8 -*-
"""
@Time : 2024/2/23 9:22 PM
@Author: imamhusan
@Des: 轮播图
"""
from fastapi import APIRouter, Request
from models.banner import Banner
from schemes.banner import CreateBanner, UpdateBanner, MultiUpdateBanner
from core.Response import success, fail, res_antd

router = APIRouter(prefix='/banner')


@router.post('', description='添加轮播图')
async def add_banner(post: CreateBanner):
    try:
        new_banner = await Banner.create(**post.dict())
        if new_banner:
            return success(data=new_banner, msg='创建成功')
        return fail(msg='创建失败')
    except Exception as e:
        return str(e)


@router.delete('/{id}', description='删除轮播图')
async def del_banner(id: int):
    try:
        del_ok = await Banner.filter(pk=id).delete()
        if del_ok:
            return success(data=del_ok, msg='删除成功')
        return fail(msg='删除失败')
    except Exception as e:
        return str(e)


@router.put('/{id}/{state}', description='修改轮播图')
async def update_banner_state(id:int, state: int):
    try:
        update_ok = await Banner.filter(pk=id).update(state=state)
        if update_ok:
            return success(data=update_ok, msg='修改成功')
        return fail(msg='修改失败')
    except Exception as e:
        return str(e)


@router.put('/multi_update_state', description='修改轮播图')
async def multi_update_state(post: MultiUpdateBanner):
    try:
        update_ok = await Banner.filter(id__in=post.ids).update(state=post.state)
        if update_ok:
            return success(data=update_ok, msg=f'「{update_ok}」条数据状态修改成功')
        return fail(msg='修改失败')
    except Exception as e:
        return str(e)


@router.put('/{id}', description='修改轮播图')
async def update_banner(id:int, post: UpdateBanner):
    try:
        data = post.dict()
        update_ok = await Banner.filter(pk=id).update(**data)
        if update_ok:
            return success(data=update_ok, msg='修改成功')
        return fail(msg='修改失败')
    except Exception as e:
        return str(e)


@router.get('', description='获取轮播图列表')
async def get_banner(req: Request):
    try:
        device = req.headers.get('device', 'mp')
        if device != 'web':
            banner_list = await Banner.filter(state=1).order_by('sort')
            return success(data=banner_list, msg='获取成功')
        else:
            query = Banner.filter(state__not=-1)
            total = await query.count()
            banner_list = await query.order_by('sort').values()
            return res_antd(data=banner_list, total=total)

    except Exception as e:
        return str(e)


@router.get('/{id}', description='获取轮播信息')
async def get_banner_info(id : int):
    try:
        banner_obj = await Banner.get_or_none(pk=id)
        if banner_obj:
            return success(data=banner_obj, msg='获取成功')
        return fail(msg='获取失败')
    except Exception as e:
        return str(e)
